package com.camel.gateway.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author camel
 */
@ControllerAdvice
@RestController
public class GlobalException {
    @ResponseBody
    @ExceptionHandler
    public Result handlerException(Exception e) {

        // 打印堆栈，以供调试
        e.printStackTrace();
        // 不同异常返回不同状态码
        Result re = null;
        // 如果是未登录异常
        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            re = ResultUtil.error(500, "未登录");
        }
        // 如果是角色异常s
        else if (e instanceof NotRoleException) {
            NotRoleException ee = (NotRoleException) e;
            re = ResultUtil.error(500, "无此角色");
        // 如果是权限异常
        } else if (e instanceof NotPermissionException) {
            NotPermissionException ee = (NotPermissionException) e;
            re = ResultUtil.error(500, "无此权限");
        } else {    // 普通异常, 输出：500 + 异常信息
            re = ResultUtil.error(500, e.getMessage());
        }

        // 返回给前端
        return re;
    }
}
